var $ = window.$;
var jade = require('jade');
var animate = require('../../util/animate');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var io = require('../io/ui');
var notify = require('../notify/ui');
var event = require('../../core/event');
var config = require('../../core/config');
var slide = require('../../core/slide');


var _init = false;


var ret = {
	init: function(){
		if(_init){
			return;
		}
		this.slideId = [];

		event.bind(event.events.key.up, 'meta_ui', this);
		event.lock('key', 'meta_ui');

		_init = true;
	},

	setManager: function(ma){
		this.manager = ma;
	},

	onEvent: function(e, param) {
		if(e == event.events.global.dialog){
			this.hide();
		}else if(e == event.events.key.up){
			if(param.key == 27){
				this.hide();
			}
		}
	},

	getData: function(){
		if(!_init){
			return null;
		}
		var tab = this.parent.find('.g_tab .curr').index();
		var input = this.parent.find('input');
		if(tab == 0){
			this._meta.title = input.eq(0).val();
			this._meta.artist = input.eq(1).val();
			this._meta.source = input.eq(2).val();
		}else{
			this._meta.title2 = input.eq(0).val();
			this._meta.artist2 = input.eq(1).val();
			this._meta.source2 = input.eq(2).val();
		}
		this._meta.creator = input.eq(3).val();
		this._meta.version = input.eq(4).val();

		var self = this;
		input = this.parent.find('select');
		input.each(function(i, item){
			var _item = $(item);
			self._meta[_item.attr('name')] = _item.val();
		});
		var cover = this.parent.find('.cover .g_img');
		this._meta["background"] = this.tempCover || '';
		if(this._meta["mode"] == "3"){
			var speed = this.parent.find('#speed_tip').html();
			this._meta["speed"] = +speed;
		}else{
			var col = this.parent.find('#column_tip').html();
			this._meta["column"] = +col;
		}

		this._meta.isNew = this.isNew;
		return this._meta;
	},

	changeTab: function(idx){
		var inputs = this.parent.find('input');
		//寄存当前页, 显示目标页
		if(idx == 0){
			this._meta.title2 = inputs.eq(0).val();
			this._meta.artist2 = inputs.eq(1).val();
			this._meta.source2 = inputs.eq(2).val();

			inputs.eq(0).val(this._meta.title);
			inputs.eq(1).val(this._meta.artist);
			inputs.eq(2).val(this._meta.source);
		}else{
			this._meta.title = inputs.eq(0).val();
			this._meta.artist = inputs.eq(1).val();
			this._meta.source = inputs.eq(2).val();

			inputs.eq(0).val(this._meta.title2);
			inputs.eq(1).val(this._meta.artist2);
			inputs.eq(2).val(this._meta.source2);
		}
	},

	show: function(isNew){
		this.isNew = isNew;
		var tmpl = jade.compileFile('./tmpl/meta/dialog.jade');
		var html = tmpl({config: config});
		var self = this;
		$('#dialog_layer').append(html);
		this.parent = $('#dialog_meta');

        var meta = self.manager._getMeta();
		this._meta = util.cloneObject(meta || {});

		if(meta){
			this._meta["title"] = util.getJsonChainValue(meta, 'song.title') || '';
			this._meta["artist"] = util.getJsonChainValue(meta, 'song.artist') || '';
			this._meta["source"] = util.getJsonChainValue(meta, 'song.source') || '';
			this._meta["title2"] = util.getJsonChainValue(meta, 'song.org.title') || '';
			this._meta["artist2"] = util.getJsonChainValue(meta, 'song.org.artist') || '';
			this._meta["source2"] = util.getJsonChainValue(meta, 'song.org.source') || '';
		}

		if(!isNew){
			if(meta){
				if(meta.mode == 3){
					this.parent.attr('class', 'g_dialog catch');
				}else if(meta.mode < 3){
					this.parent.attr('class', 'g_dialog key');
				}else{
					this.parent.attr('class', 'g_dialog');
				}
			}
		}
		this.parent.on('click','.g_barhead i', function () {
			self.hide();
		});
		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'cover'){
				io.getImgPath().then(function(path){
					if(!path) return;
					self.tempCover = path;
					self.parent.find('.cover .g_img').css('backgroundImage', 'url("'+path+'")');
				});
			}else if(type == 'ok'){
				self.manager._save(self.isNew);  //先save，再hide，否则就拿不到数据了
				if(self.isNew){
					event.bindOnce(event.events.global.dialog, 'meta_ui', self);
				}else{
					self.hide();
				}
			}else if(type == 'close'){
				self.hide();
			}
		});

		this.parent.find('.g_tab').on('click', 'span', function(e) {
			var target = $(this);
			var parent = target.parent();
			parent.find('.curr').removeClass('curr');
			target.addClass('curr');
			var idx = target.index();
			self.changeTab(idx);
		});

		this.parent.find('select').change(function() {
			if(!isNew){
				notify.addNotify({
					msg: config.i18n("tip06")
				});
				return;
			}
			//切换模式
			var mode = +$(this).val();
			if(mode == 3){
				self.parent.attr('class', "g_dialog catch");
			}else if(mode < 3){
				self.parent.attr('class', "g_dialog key");
			}else if(mode ==4){
                self.parent.attr('class', "g_dialog pad");
			}else{
                self.parent.attr('class', "g_dialog");
            }
		});

		var sliders = this.parent.find('.g_slide');
		sliders.eq(0).attr('id', 'dialog_meta_key');
		sliders.eq(1).attr('id', 'dialog_meta_speed');
		//column
		var id = slide.on({
			parent: sliders.eq(0),
			min: 4,
			max: 10,
			onchange: function (val) {
				self.parent.find("#column_tip").html(Math.round(val));
			}
		});
		this.slideId.push(id);

		//speed
		id = slide.on({
			parent: sliders.eq(1),
			min: 1,
			max: 10,
			onchange: function (val) {
				self.parent.find("#speed_tip").html(Math.round(val));
			}
		});
		this.slideId.push(id);

		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent).then(function() {
			var inputs = self.parent.find('input');
			if(isNew){
				var user = config.getVal(config.ITEM.USER);
				if(user){
					inputs.eq(3).val(user);
				}
				return;
			}
			var meta = self.manager._getMeta();
			if(!meta){
				return;
			}


			if(meta.background){
				self.tempCover = self.manager._getPath(meta.background);
				self.parent.find('.cover .g_img').css('backgroundImage', 'url("'+self.tempCover+'")');
			}

			inputs.eq(0).val(self._meta.title || '');
			inputs.eq(1).val(self._meta.artist || '');
			inputs.eq(2).val(self._meta.source || '');
			inputs.eq(3).val(meta.creator || '');
			inputs.eq(4).val(meta.version || '');
			self.parent.find('select').val(meta.mode || 0);
			if(meta.mode == 3){
				var speed = util.getJsonChainValue(meta, 'mode_ext.speed');
				slide.setVal(self.slideId[1], speed || 1, true);
			}else if(meta.mode < 3){
				var col = util.getJsonChainValue(meta, 'mode_ext.column');
				slide.setVal(self.slideId[0], col || 4, true);
			}
		});
	},

	hide: function(){
		if(!_init || !this.parent){
			return;
		}
		var self = this;
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			event.unbindByKey('meta_ui');
			uiUtil.dialogDec();
			slide.off(self.slideId[0]);
			slide.off(self.slideId[1]);
		});
		event.unlock();

		_init = false;
	},

    confirmGuide: function() {
        if(window.confirm(config.i18n("meta11"))){
            event.trigger(event.events.dialog.create);
        }
    }

};

module.exports = ret;